package com.zhenyi.tuangou.index;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Clear;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.utils.DateUtils;
import com.zhenyi.common.model.TgCart;
import com.zhenyi.common.model.TgOrder;
import com.zhenyi.common.model.TgProduct;
import com.zhenyi.common.model.TgProductItem;
import com.zhenyi.common.model.TgUser;
import com.zhenyi.common.model.TgUserProductOrder;
import com.zhenyi.tuangou.core.OrderUtils;

public class CartController extends TGController {

	/**
	 * 加入商品到购物车
	 */
	public void addProductToCar() {
		Long productId = getParaToLong("productId");
		Long productItemId = getParaToLong("productItemId");
		int num = getParaToInt("num", 1);
		if (productId == null || productItemId == null) {
			renderFailure();
			renderError(500);
			return;
		}
		addCart(productId, num, productItemId);
		setAttr("msg", "ok");
		//redirect("/tg/shoppingCar/list");
		renderSuccess();
	}

	/**
	 * 用户购物车内的商品
	 */
	@Clear
	public void list() {
		TgUser user = getUser();
		// Long userId = (long) 20180709;
		Kv cond = Kv.by("userId", user.getId());
		SqlPara sql = Db.getSqlPara("findShoppingCarByUserId", cond);
		List<Record> list = Db.find(sql);
		for (Record record : list) {
			Kv cond1 = Kv.by("productId", record.getLong("productId"));
			SqlPara sqlPara = Db.getSqlPara("findProductItem", cond1);
			List<Record> list1 = Db.find(sqlPara);// 产品规格列表
			record.set("productItem", list1);
		}
		setAttr("products", list);
		// renderJson(list);
		render("/res/cart.html");
	}

	/**
	 * 删除购物车内的商品 或者清空
	 */
	public void dropShoppingCarProduct() {
		String shoppingCarIds = getPara("id");// 选中的id
		dropCart(shoppingCarIds);
		redirect("/shoppingCar/list");
	}

	/**
	 * 更新购物车内商品信息---规格数量类
	 */
	public void updateCart() {
		Long cartId = getParaToLong("id");
		Integer productNum = getParaToInt("productNum");
		Long productItemId = getParaToLong("productItemId");
		if (cartId == null) {
			renderError(500);
			return;
		}
		TgCart tgCart = TgCart.dao.findById(cartId);
		TgUser user = getUser();
		if (productNum == null && productItemId == null) {
			renderError(500);
			return;
		} else if (productNum != null) {// 更新数量
			if (!tgCart.getUserId().equals(user.getId())) {
				renderError(500);
				return;
			}
			if (productNum == 0) {
				dropCart(cartId + ";");
			}
			tgCart.setProductNum(productNum);
			tgCart.update();
		} else if (productItemId != null) {// 更新规格
			if (!tgCart.getUserId().equals(user.getId())) {
				renderError(500);
				return;
			}
			tgCart.setProductItemId(productItemId);
			tgCart.update();
		}
		// redirect("/shoppingCar/list");
		renderSuccess();
	}

	/**
	 * 购物车结算
	 */
	public void settlement() {
		String shoppingCarIds = getPara("ids");
		if (StrKit.isBlank(shoppingCarIds)) {
			renderError(404);
			return;
		}
		TgOrder order = new TgOrder();
		order = addSettlementOrder(shoppingCarIds);
		if (order == null) {
			renderFailure("商品已下架或库存不足");
			return;
		}
		// 用户判断
		if (!order.getUserId().equals(getUser().getId())) {
			order.print();
			renderError(401);
			return;
		}
		String ids[] = shoppingCarIds.split(";");
		List<TgProduct> list = new ArrayList<TgProduct>();
		for (String i : ids) {
			Long id = Long.parseLong(i);
			TgCart tgCart = TgCart.dao.findById(id);
			TgProduct tgProduct = TgProduct.dao.findById(tgCart.getProductId());
			list.add(tgProduct);
		}
		dropCart(shoppingCarIds);
		setAttr("products", list);// 商品信息表
		setAttr("order", order);// 订单信息
		setAttr("orderCode", hashids.encode(order.getId()));// 订单加密id
		render("/res/orderConfirm.html");

	}

	/**
	 * 删除购物车内的商品 或者清空
	 * 
	 * @param shoppingCarIds
	 */
	protected void dropCart(String shoppingCarIds) {
		Long userId = getUser().getId();
		Kv cond = Kv.by("userId", userId);
		if (shoppingCarIds != null) {
			String ids[] = shoppingCarIds.split(";");
			for (String i : ids) {
				Long id = Long.parseLong(i);
				cond.set("id", id);
				SqlPara sql = Db.getSqlPara("findShoppingCarByUserId", cond);
				List<Record> list = Db.find(sql);
				for (Record record : list) {
					TgCart.dao.deleteById(record.getLong("id"));
				}
			}
		} else {
			SqlPara sql = Db.getSqlPara("findShoppingCarByUserId", cond);
			List<Record> list = Db.find(sql);
			for (Record record : list) {
				TgCart.dao.deleteById(record.getLong("id"));
			}
		}
	}

	/**
	 * 购物车结算下单
	 * 
	 * @param num
	 * @param groupProductId
	 * @return
	 */
	protected TgOrder addSettlementOrder(String shoppingCarIds) {
		TgOrder order = new TgOrder();
		String ids[] = shoppingCarIds.split(";");
		boolean flag = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {

				order.save();
				int totalPrice = 0;// 多个商品 订单总价格
				StringBuffer sb = new StringBuffer();
				for (String i : ids) {

					Long id = Long.parseLong(i);
					TgCart tgCart = TgCart.dao.findById(id);
					if (tgCart == null) {
						return false;
					}
					if (tgCart.getStatus() != 1) {
						return false;
					}
					TgProductItem tgProductItem = TgProductItem.dao.findById(tgCart.getProductItemId());
					totalPrice += tgCart.getProductNum() * tgProductItem.getPrice();// 商品价格
					TgUserProductOrder tgUserProductOrder = new TgUserProductOrder();
					tgUserProductOrder.setOrderId(order.getId());
					tgUserProductOrder.setUserId(getUser().getId());
					tgUserProductOrder.setName(getUser().getName());
					tgUserProductOrder.setProductId(tgCart.getProductId());
					tgUserProductOrder.setTotalFee(tgCart.getProductNum() * tgProductItem.getPrice());// 商品价格
					tgUserProductOrder.setProductNum(tgCart.getProductNum());// 商品数量
					tgUserProductOrder.setProductItemId(tgCart.getProductItemId());
					tgUserProductOrder.save();

					sb.append(tgCart.getProductId()).append(";");
				}
				String time = DateUtils.dateFormat(new Date(), "YYYYMMddhhmmss");
				String hash = hashids.encode(order.getId());
				String outTradeNo = time + hash;
				order.setStartTime(new Date());
				order.setOutTradeNo(outTradeNo);// 订单号
				order.setTotalFee(totalPrice);// 总价
				order.setStatus(TgOrder.STATUS_NO_PAY);// 未支付
				order.setUserId(getUser().getId());// 用户id
				order.setExtra(OrderUtils.SETTLEMENT + sb.toString());
				order.update();
				return true;
			}
		});
		if (flag)
			return order;
		else
			return null;
	}

	/**
	 * 加入商品到购物车
	 * 
	 * @param productId
	 * @param num
	 */
	protected void addCart(long productId, int num, long productItemId) {
		TgUser user = getUser();
		Kv cond = Kv.by("userId", user.getId());
		cond.set("productId", productId);
		cond.set("productItemId", productItemId);
		SqlPara sqlPara = Db.getSqlPara("findProductInCar", cond);
		TgCart record = TgCart.dao.findFirst(sqlPara);
		if (record == null) {
			TgCart tgCart = new TgCart();
			tgCart.setUserId(user.getId());
			tgCart.setProductId(productId);
			tgCart.setProductNum(num);
			tgCart.setProductItemId(productItemId);
			tgCart.save();
		} else {
			Long id = record.getId();
			TgCart tgCart = TgCart.dao.findById(id);
			record.setProductNum(tgCart.getProductNum() + num);
			record.update();
		}
	}
}